package filter;

import com.wuda.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter(filterName = "AdminFilter", urlPatterns = {"/admin/*"})
public class AdminFilter implements Filter {
	@Override
	public void destroy() {
		// 销毁代码，如果有需要
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session = req.getSession(false); // 获取现有 session，如果没有则返回 null
		if (session == null || session.getAttribute("user") == null) {
			System.out.println("AdminFilter-->用户未登录，重定向到首页");
			// 如果没有 session 或没有登录用户，重定向到首页
			resp.sendRedirect(req.getContextPath() + "/index.jsp");
			return;
		}

		User user = (User) session.getAttribute("user");
		if (!"admin".equals(user.getRole())) {
			System.out.println("AdminFilter-->用户不是管理员角色，重定向到首页");
			// 如果用户不是管理员角色，重定向到首页
			resp.sendRedirect(req.getContextPath() + "/index.jsp");
			return;
		}
		// 如果通过验证，继续处理请求
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig fConfig) throws ServletException {
		// 初始化代码，如果有需要
	}
}
